//
//  TSCMyUploadPicDialog.m
//  Tsc_IOS
//
//  Created by ZhengRui on 15/8/28.
//  Copyright © 2015年 idream. All rights reserved.
//
// == TODO
// -- 1. 只让用户选择相片，而不包括视频
// -- 2. 验证选择顺序。经验证，NSArray中返回的info数组符合用户选择的顺序（EliteReader是个好东西！可以查看图片名称）
// -- 3. 如何将UIImagePickerController和ELCImagePickerController的delegate整合起来？因为目前拍照用的是前者，而从相册中选择用的是后者

#import <Foundation/Foundation.h>
#import "TSCMyUploadPicDialog.h"
#import "TSCMyDialog.h"
#import "TSCMyUIUtil.h"
#import "TSCMyUtil.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "ELCImagePickerController.h"

@implementation TSCMyUploadPicDialog {
    TSCMyDialog * _dialog;
    
    UIImageView * _rightIcon; // 右侧倒三角图标
}

- (id)init {
    self = [super init];
    if (self) {
        [self initMyUploadPicDialog];
    }
    return self;
}

// 当从Storyboard加载时，必须重写此方法，否则将导致类属性无法初始化
// 在Storyboard中使用自定义UIView的操作方法：
// 1. 继承UIView，新写一个子view：MyView
// 2. 在storyboard中，拖拽一个view控件，并设置其customClass为MyView
// 3. 在MyView中实现initWithCoder()方法。示例如下：
- (id) initWithCoder:(NSCoder *)aDecoder {
    // 调用父类初始化方法
    self = [super initWithCoder:aDecoder];
    if (self) {
        // 运行自定义初始化方法
        [self initMyUploadPicDialog];
    }
    return self;
}

- (void) initMyUploadPicDialog {
    // 设置各属性的默认值
    _title = @"";
    _bodyView = nil;
    _textSize = [TSCMyUIUtil getSystemDefaultFont].pointSize;
    _isMultiPicker = NO;
    _maxPhotoPickNum = 1; // 默认只能选择一张图片
    _hasRightDownTriangleIcon = YES; // 默认具有右侧倒三角
    
    // 设置textField默认样式
    self.borderStyle = UITextBorderStyleRoundedRect; // 设置borderStyle。注：设置了默认的borderStyle后，文字的padding也会自动设置
    self.font = [TSCMyUIUtil getSystemDefaultFont]; // 设置字体
    _rightIcon = [TSCMyUIUtil addDownTriangleIconToView:self direction:IconDirectionRight]; // 添加右侧倒三角
    self.delegate = self; // 设置textField代理，用来在textField点击时，阻止键盘弹出
    [self addTarget:self action:@selector(selfOnClick) forControlEvents:UIControlEventTouchDown]; // 注册事件——点击显示dialog
}

#pragma mark 公共方法

- (void) dismiss {
    [_dialog dismiss];
}


#pragma mark target事件响应

// 当自身被点击时
- (void) selfOnClick {
    // 判断是否继续进行后续显示。如果外部使用者设置了该回调，且结果表明不显示（比如顾客求购创建界面，如果已经选择了3张图片，就不能再弹出图片选择dialog了），直接返回
    if (_isShowPickerDialog && _isShowPickerDialog() == NO) {
        return;
    }
    
    // 创建dialog
    _dialog = [[TSCMyDialog alloc]init];
    _dialog.textSize = _textSize;
    _dialog.titleText = _title;
    _dialog.customView = _bodyView;
    
    // 左按钮：拍照
    BOOL isCameralAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
    if (isCameralAvailable) {
        _dialog.leftBtnText = NSLocalizedString(@"btn_take_photo", nil);
        
        __weak typeof (self) _weakSelf = self;
        _dialog.leftBtnOnClickListener = ^(UIButton * btn, TSCMyDialog * dialog) {
            typeof (self) _strongSelf = _weakSelf;
            if (_strongSelf) {
                // 创建相机
                UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
                cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
                cameraUI.mediaTypes =[[NSArray alloc] initWithObjects: (NSString *)kUTTypeImage, nil];
                cameraUI.allowsEditing = NO; // 注：不允许编辑，而将编辑留给自定义的VC进行处理
                cameraUI.delegate = _strongSelf;
                
                [[TSCMyUtil getCurrentViewController] presentViewController:cameraUI animated:YES completion:nil];
            } else {
                NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
            }
        };
    } else {
        [TSCMyUIUtil popErrWithResourceKey:@"err_cameral_unavailable"];
    }
    
    // 右按钮：从相册选择
    BOOL isPhotoLibraryAvailable = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary];
    if (isPhotoLibraryAvailable) {
        _dialog.rightBtnText = NSLocalizedString(@"btn_select_from_gallery", nil);
        
        __weak typeof (self) _weakSelf = self;
        _dialog.rightBtnOnClickListener = ^(UIButton * btn, TSCMyDialog * dialog) {
            typeof (self) _strongSelf = _weakSelf;
            if (_strongSelf) {
                // 创建相片选择器
                
                // 方法一：使用系统默认的相片选择器（只能单选）
                // 注：当选择一张相片时，支持编辑
                if (_maxPhotoPickNum == 1) {
                    UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
                    cameraUI.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    cameraUI.mediaTypes =[[NSArray alloc] initWithObjects: (NSString *)kUTTypeImage, nil];
                    cameraUI.allowsEditing = NO; // 注：不允许编辑，而将编辑留给自定义的VC进行处理
                    cameraUI.delegate = _strongSelf;
                    [[TSCMyUtil getCurrentViewController] presentViewController:cameraUI animated:YES completion:nil];
                }
                
                // 方法二：使用第三方相片选择器（支持多选）
                // 注：当选择多张相片时，不支持编辑
                else {
                    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
                    elcPicker.maximumImagesCount = _strongSelf->_maxPhotoPickNum; //Set the maximum number of images to select, defaults to 4
                    elcPicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
                    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
                    elcPicker.onOrder = YES; //For multiple image selection, display and return selected order of images
                    elcPicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *)kUTTypeImage, nil]; // 只选择相片
                    elcPicker.imagePickerDelegate = _strongSelf;
                    [[TSCMyUtil getCurrentViewController] presentViewController:elcPicker animated:YES completion:nil];
                }
            }
            else {
                NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
            }
        };
    } else {
        [TSCMyUIUtil popErrWithResourceKey:@"err_gallery_unavailable"];
    }
    
    // 如果既没有照相机，又没有相册，提示用户
    if (isCameralAvailable == NO && isPhotoLibraryAvailable == NO) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_cameral_and_gallery_unavailable"];
    }
    
    // 显示dialog
    [_dialog show];
}

#pragma mark delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return NO; // 点击textField自身时，阻止键盘弹出
}

// 系统默认相片选择器：取消
- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    //    if (_imagePickerControllerDidCancel) {
    //        _imagePickerControllerDidCancel(picker);
    //    }
    if (_myImagePickerControllerDidCancel) {
        _myImagePickerControllerDidCancel(picker);
    }
}

// 系统默认相片选择器：选中
- (void) imagePickerController: (UIImagePickerController *) picker didFinishPickingMediaWithInfo: (NSDictionary *) info {
    //    if (_imagePickerControllerDidFinishPickingMediaWithInfo) {
    //        _imagePickerControllerDidFinishPickingMediaWithInfo(picker, info);
    //    }
    if (_myImagePickerControllerDidFinishPickingMediaWithInfo) {
        _myImagePickerControllerDidFinishPickingMediaWithInfo(picker, [NSArray arrayWithObject:info]); // 注：将dic放在arr中，以匹配参数类型
    }
}

// 第三方相片选择器：取消
- (void) elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
    //    if (_elcImagePickerControllerDidCancel) {
    //        _elcImagePickerControllerDidCancel(picker);
    //    }
    if (_myImagePickerControllerDidCancel) {
        _myImagePickerControllerDidCancel(picker);
    }
}

// 第三方相片选择器：选中
- (void) elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)infoArr {
    //    if (_elcImagePickerControllerDidFinshPickingMediaWithInfo) {
    //        _elcImagePickerControllerDidFinshPickingMediaWithInfo(picker, info);
    //    }
    if (_myImagePickerControllerDidFinishPickingMediaWithInfo) {
        _myImagePickerControllerDidFinishPickingMediaWithInfo(picker, infoArr); // 注：将dic放在arr中，以匹配参数类型
    }
}

#pragma mark Getters & Setters

- (void) setHasRightDownTriangleIcon:(BOOL)hasRightDownTriangleIcon {
    _hasRightDownTriangleIcon = hasRightDownTriangleIcon;
    
    // 同步显示/隐藏右侧倒三角
    if (hasRightDownTriangleIcon) {
        _rightIcon.hidden = NO;
    } else {
        _rightIcon.hidden = YES;
    }
}

@end